<template>
  <div v-if="visible" class="room-dialog-overlay" @click="handleOverlayClick">
    <div class="room-dialog" @click.stop>
      <div class="room-dialog-header">
        <h2>房间管理</h2>
        <button class="close-btn" @click="$emit('close')">
          <span>&times;</span>
        </button>
      </div>
      
      <div class="room-dialog-content">
        <!-- 标签页切换：创建 / 加入 -->
        <div class="tab-container">
          <button 
            class="tab-btn" 
            :class="{ active: activeTab === 'create' }"
            @click="activeTab = 'create'"
          >
            创建房间
          </button>
          <button 
            class="tab-btn" 
            :class="{ active: activeTab === 'join' }"
            @click="activeTab = 'join'"
          >
            加入房间
          </button>
        </div>
        
        <!-- 创建房间表单 -->
        <div v-if="activeTab === 'create'" class="form-container">
          <div class="form-group">
            <label for="roomName">房间名称</label>
            <input 
              id="roomName"
              v-model="createForm.roomName" 
              type="text" 
              placeholder="请输入房间名称"
              maxlength="20"
            />
          </div>
          
          <div class="form-group">
            <label for="playerName">玩家昵称</label>
            <input 
              id="playerName"
              v-model="createForm.playerName" 
              type="text" 
              placeholder="请输入你的昵称"
              maxlength="10"
            />
          </div>
          
          <div class="form-group">
            <label for="maxPlayers">最大玩家数</label>
            <select id="maxPlayers" v-model="createForm.maxPlayers">
              <option value="2">2人</option>
              <option value="3">3人</option>
              <option value="4">4人</option>
              <option value="5">5人</option>
            </select>
          </div>
          
          <div class="form-group">
            <label for="gameTime">游戏时长（分钟）</label>
            <select id="gameTime" v-model="createForm.gameTime">
              <option value="1">1分钟</option>
              <option value="2">2分钟</option>
              <option value="3">3分钟</option>
              <option value="5">5分钟</option>
            </select>
          </div>
          
          <button 
            class="submit-btn create-btn" 
            @click="handleCreateRoom"
            :disabled="!isCreateFormValid || isCreating"
          >
            {{ isCreating ? '创建中...' : '创建房间' }}
          </button>
        </div>
        
        <!-- 加入房间表单 -->
        <div v-if="activeTab === 'join'" class="form-container">
          <div class="form-group">
            <label for="roomId">房间ID</label>
            <input 
              id="roomId"
              v-model="joinForm.roomId" 
              type="text" 
              placeholder="请输入房间ID"
              maxlength="10"
            />
          </div>
          
          <!-- 加入房间时不再填写玩家昵称，自动使用当前用户昵称 -->
          
          <button 
            class="submit-btn join-btn" 
            @click="handleJoinRoom"
            :disabled="!isJoinFormValid || isJoining"
          >
            {{ isJoining ? '加入中...' : '加入房间' }}
          </button>
        </div>
      </div>
      
      <!-- 错误信息显示 -->
      <div v-if="errorMessage" class="error-message">
        {{ errorMessage }}
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed } from 'vue'
import { useSocketStore } from '@/stores/socket'
import { useGameStore } from '@/stores/game'

export default {
  name: 'RoomDialog',
  // 输入：可见性与模拟模式开关
  props: { visible: { type: Boolean, default: false }, mock: { type: Boolean, default: true } },
  // 输出：关闭、创建成功、加入成功事件
  emits: ['close', 'room-created', 'room-joined'],
  setup(props, { emit }) {
    const socketStore = useSocketStore()
    const gameStore = useGameStore()
    
    const activeTab = ref('create')
    const isCreating = ref(false)
    const isJoining = ref(false)
    const errorMessage = ref('')
    
    // 创建表单与加入表单
    const createForm = ref({ roomName: '', playerName: '', maxPlayers: 5, gameTime: 2 })
    const joinForm = ref({ roomId: '' })
    
    // 表单校验
    const isCreateFormValid = computed(() => createForm.value.roomName.trim() && createForm.value.playerName.trim())
    const isJoinFormValid = computed(() => joinForm.value.roomId.trim())
    
    // 创建房间
    const handleCreateRoom = async () => {
      if (!isCreateFormValid.value) return
      isCreating.value = true
      errorMessage.value = ''
      try {
        const roomData = {
          roomName: createForm.value.roomName.trim(),
          playerName: createForm.value.playerName.trim(),
          maxPlayers: parseInt(createForm.value.maxPlayers),
          gameTime: parseInt(createForm.value.gameTime) * 60
        }
        if (props.mock) {
          setTimeout(() => {
            const fakeRoomId = Math.random().toString(36).slice(2, 8).toUpperCase()
            gameStore.currentPlayer = roomData.playerName
            gameStore.gameTime = roomData.gameTime
            emit('room-created', { roomId: fakeRoomId, roomName: roomData.roomName, playerName: roomData.playerName })
            isCreating.value = false
          }, 600)
          return
        }
        const success = socketStore.createRoom(roomData)
        if (success) {
          socketStore.once('RoomCreated', (data) => {
            if (data.success) {
              gameStore.currentPlayer = roomData.playerName
              gameStore.gameTime = roomData.gameTime
              emit('room-created', { roomId: data.roomId, roomName: roomData.roomName, playerName: roomData.playerName })
            } else { errorMessage.value = data.message || '创建房间失败' }
            isCreating.value = false
          })
          socketStore.once('RoomError', (data) => { errorMessage.value = data.message || '创建房间时发生错误'; isCreating.value = false })
        } else { errorMessage.value = '创建房间失败，请稍后重试'; isCreating.value = false }
      } catch (error) { errorMessage.value = '创建房间失败：' + error.message; isCreating.value = false }
    }
    
    // 加入房间
    const handleJoinRoom = async () => {
      if (!isJoinFormValid.value) return
      isJoining.value = true
      errorMessage.value = ''
      try {
        const roomData = { roomId: joinForm.value.roomId.trim(), playerName: gameStore.currentPlayer || '玩家' }
        if (props.mock) {
          setTimeout(() => {
            const fakeRoomName = `房间-${roomData.roomId}`
            const fakeGameTime = 120
            gameStore.currentPlayer = roomData.playerName
            gameStore.gameTime = fakeGameTime
            emit('room-joined', { roomId: roomData.roomId, roomName: fakeRoomName, playerName: roomData.playerName, roomData: { maxPlayers: 5 } })
            isJoining.value = false
          }, 600)
          return
        }
        const success = socketStore.joinRoom(roomData)
        if (success) {
          socketStore.once('RoomJoined', (data) => {
            if (data.success) {
              gameStore.currentPlayer = roomData.playerName
              // 只有在数据中明确提供游戏时间时才设置，避免覆盖正确的时间
              if (data.gameTime && typeof data.gameTime === 'number') {
                gameStore.gameTime = data.gameTime
              }
              emit('room-joined', { roomId: roomData.roomId, playerName: roomData.playerName, roomData: data.roomData })
            } else { errorMessage.value = data.message || '加入房间失败' }
            isJoining.value = false
          })
          socketStore.once('RoomError', (data) => { errorMessage.value = data.message || '加入房间时发生错误'; isJoining.value = false })
        } else { errorMessage.value = '加入房间失败，请稍后重试'; isJoining.value = false }
      } catch (error) { errorMessage.value = '加入房间失败：' + error.message; isJoining.value = false }
    }
    
    const handleOverlayClick = () => { emit('close') }
    
    return { activeTab, createForm, joinForm, isCreating, isJoining, errorMessage, isCreateFormValid, isJoinFormValid, handleCreateRoom, handleJoinRoom, handleOverlayClick }
  }
}
</script>

<style scoped>
.room-dialog-overlay { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background-color: rgba(0, 0, 0, 0.5); display: flex; align-items: center; justify-content: center; z-index: 1000; }
.room-dialog { background: white; border-radius: 12px; box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04); width: 90%; max-width: 480px; max-height: 90vh; overflow-y: auto; }
.room-dialog-header { display: flex; justify-content: space-between; align-items: center; padding: 24px 24px 0 24px; border-bottom: 1px solid #e5e7eb; padding-bottom: 16px; }
.room-dialog-header h2 { margin: 0; font-size: 1.5rem; font-weight: 600; color: #111827; }
.close-btn { background: none; border: none; font-size: 1.5rem; cursor: pointer; color: #6b7280; padding: 4px; border-radius: 4px; transition: color 0.2s; }
.close-btn:hover { color: #374151; }
.room-dialog-content { padding: 24px; }
.tab-container { display: flex; margin-bottom: 24px; border-bottom: 1px solid #e5e7eb; }
.tab-btn { flex: 1; padding: 12px 16px; background: none; border: none; cursor: pointer; font-size: 1rem; font-weight: 500; color: #6b7280; border-bottom: 2px solid transparent; transition: all 0.2s; }
.tab-btn:hover { color: #374151; }
.tab-btn.active { color: #3b82f6; border-bottom-color: #3b82f6; }
.form-container { display: flex; flex-direction: column; gap: 20px; }
.form-group { display: flex; flex-direction: column; gap: 8px; }
.form-group label { font-weight: 500; color: #374151; font-size: 0.875rem; }
.form-group input, .form-group select { padding: 12px 16px; border: 1px solid #d1d5db; border-radius: 8px; font-size: 1rem; transition: border-color 0.2s, box-shadow 0.2s; }
.form-group input:focus, .form-group select:focus { outline: none; border-color: #3b82f6; box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1); }
.submit-btn { padding: 12px 24px; border: none; border-radius: 8px; font-size: 1rem; font-weight: 500; cursor: pointer; transition: all 0.2s; margin-top: 8px; }
.submit-btn:disabled { opacity: 0.6; cursor: not-allowed; }
.create-btn { background-color: #3b82f6; color: white; }
.create-btn:hover:not(:disabled) { background-color: #2563eb; }
.join-btn { background-color: #10b981; color: white; }
.join-btn:hover:not(:disabled) { background-color: #059669; }
.error-message { margin: 16px 24px 24px 24px; padding: 12px 16px; background-color: #fef2f2; border: 1px solid #fecaca; border-radius: 8px; color: #dc2626; font-size: 0.875rem; }
@media (max-width: 640px) { .room-dialog { width: 95%; margin: 20px; } .room-dialog-header, .room-dialog-content { padding: 16px; } }
</style> 